<template>
  <div id="EquipmentBookingPage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">报修工单筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">时间范围</span>
          <el-date-picker
            class="item-input"
            v-model="rangeTime"
            type="daterange"
            format="YYYY/MM/DD"
            value-format="x"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            @change="searchHandle"
          />
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">报修工单列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          border
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="content" label="内容" />
          <el-table-column prop="startTime" label="开始时间">
            <template #default="scope">
              {{ formatDate(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间">
            <template #default="scope">
              {{ formatDate(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="maintainerCode" label="处理人" />
          <el-table-column label="状态">
            <template #default="scope">
              <div :class="scope.row.status">
                {{ statusMap[scope.row.status as keyof typeof statusMap] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <div class="table-btn" @click="handle(scope.row)">去处理</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.page"
        :total="pagination.totalElements"
        :page-size="pagination.size"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 去处理弹框 -->

    <el-dialog
      class="self-dialog"
      v-model="handleDialogVisible"
      title="去处理"
      width="50%"
    >
      <div class="handle-content">
        您正在处理报修工单：{{ handleRow?.content }}
      </div>
      <el-form
        ref="handleFormRef"
        :model="handleForm"
        :rules="handleFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="handleForm.status" placeholder="请选择处理状态">
            <el-option label="进行中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理时间" prop="endTime">
          <el-date-picker
            v-model="handleForm.endTime"
            type="date"
            format="YYYY/MM/DD"
            value-format="x"
            placeholder="请选择处理结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="处理备注" prop="processingNote">
          <el-input
            v-model="handleForm.processingNote"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitHandleForm"
            :loading="handleFormLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { formatDate } from "@/assets/js/utils";
import { PaginationType } from "@/api/globalType";
import {
  getRepairOrdersPageAPI,
  updateRepairOrderStatusAPI,
} from "@/api/service/repairWorkOrder";
import {
  RepairWorkOrderType,
  GetRepairOrdersPageType,
  RepairWorkOrderStatus,
} from "@/api/types/repairWorkOrder";

// 获取当前用户信息
const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");

// 状态映射
const statusMap = {
  IN_PROGRESS: "进行中",
  COMPLETED: "已完成",
};

// 表格数据
const queryParams = ref<GetRepairOrdersPageType>({
  page: 1,
  size: 10,
  deviceId: "",
  maintainerCode: userInfo?.userCode,
  startTimeFrom: null,
  startTimeTo: null,
  status: RepairWorkOrderStatus.IN_PROGRESS,
});

// 时间范围
const rangeTime = ref<[number, number]>([0, 0]);

// 分页
const pagination = ref<PaginationType>({
  page: 1,
  size: 50,
  totalElements: 0,
  totalPages: 0,
});
const tableData = ref<RepairWorkOrderType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);
function getRepairWorkOrderList() {
  // 防止并发调用
  if (listApiLoading.value) return;
  listApiLoading.value = true;

  getRepairOrdersPageAPI({
    page: queryParams.value.page,
    size: queryParams.value.size,
    deviceId: queryParams.value.deviceId,
    maintainerCode: queryParams.value.maintainerCode,
    startTimeFrom: rangeTime.value[0] || null,
    startTimeTo: rangeTime.value[1] || null,
    status: queryParams.value.status,
  })
    .then((_data: any) => {
      const data = _data.content as RepairWorkOrderType[];
      tableData.value = data;
    })
    .catch(() => {
      ElMessage.error("获取报修工单列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getRepairWorkOrderList();

// 筛选
function searchHandle() {
  pagination.value.page = 1;
  getRepairWorkOrderList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.size = size;
  pagination.value.page = 1;
  getRepairWorkOrderList();
}
// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.page = currentPage;
  getRepairWorkOrderList();
}

// 处理
const handleRow = ref<RepairWorkOrderType>();
const handleDialogVisible = ref(false);
const handleFormRef = ref();
const handleForm = ref({
  maintainerCode: "",
  status: "IN_PROGRESS",
  endTime: null,
  processingNote: "",
});
const handleFormRules = ref({
  status: [{ required: true, message: "请选择处理状态", trigger: "blur" }],
  endTime: [{ required: true, message: "请选择处理结束时间", trigger: "blur" }],
  processingNote: [
    { required: true, message: "请输入处理备注", trigger: "blur" },
  ],
});
function handle(row: RepairWorkOrderType) {
  handleRow.value = row;
  handleDialogVisible.value = true;
}
const handleFormLoading = ref(false);
function submitHandleForm() {
  handleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      handleFormLoading.value = true;
      updateRepairOrderStatusAPI({
        id: handleRow.value?.id || "",
        status: handleForm.value.status,
        endTime: handleForm.value.endTime,
        processingNote: handleForm.value.processingNote,
        maintainerCode: userInfo?.userCode,
      })
        .then(() => {
          getRepairWorkOrderList();
          handleDialogVisible.value = false;
          ElMessage.success("处理报修工单成功");
        })
        .catch(() => {
          ElMessage.error("处理报修工单失败");
        })
        .finally(() => {
          handleFormLoading.value = false;
        });
    }
  });
}
</script>

<style scoped lang="scss">
#EquipmentBookingPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    padding-top: 1rem;
    padding-left: 1rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    .item-label {
      display: inline;
      width: 10rem;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: left;
      color: $text-color-regular;
    }
    .item-input {
      width: 20rem;
    }
  }

  .search-btn {
    height: 3rem;
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    margin-top: 1rem;
    padding-left: 1rem;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .signal-status.normal {
    color: $color_success;
  }
  .signal-status.abnormal {
    color: $color_danger;
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}
.handle-content {
  margin-bottom: 2rem;
  padding-left: 3rem;
  font-size: $font-size-page-menu;
  color: $color_brand;
}
</style>
